# load packages

pacman::p_load(tidyverse, xtable)

### table A.3 (threat perceptions in different pss) ----

# load data
pools <- read_rds("data/survey.rds")

# define function to calculate share that answer with "strongly agree" (=1) or "agree" (=2)
calculate_share <- function(x) {
    mean(x %in% c(1, 2), na.rm = TRUE) %>% round(2)
}

# initialize results data frame
results <- data.frame(
    pools = numeric(),
    park = numeric(),
    supermarket = numeric()
)

# function to process set of variables
process_set <- function(df, battery, count) {
    for (i in 1:count) {
        supermarket_col <- df[[paste0("supermarket", battery, "_", i)]]
        pools_col <- df[[paste0("pool", battery, "_", i)]]
        park_col <- df[[paste0("park", battery, "_", i)]]
        
        supermarket_share <- calculate_share(supermarket_col)
        pools_share <- calculate_share(pools_col)
        park_share <- calculate_share(park_col)
        
        results <<- rbind(results, data.frame(
            pools = pools_share,
            park = park_share,
            supermarket = supermarket_share
        ))
    }
}

# process the sets of variables
process_set(pools, "1", 10)
process_set(pools, "2", 4)

# assign appropriate row names
rownames(results) <- c("reckless behavior common", "frequent criminal incidents", "frequent sexual harassment",
                       "women must be cautious", "feel insecure here", "avoid due to others' behavior",
                       "increasingly feel foreign", "frequent cultural conflicts", "feel uncomfortable due to foreigners",
                       "increasing discomfort since 2015", "often discussions in media", "public debates about this place",
                       "public debates polarized", "should talk more about this place")

# convert data frame to LaTeX table
output <- xtable(results, 
                 align = "lccc",
                 caption = "Threat perceptions in different public social spaces", 
                 label = "tab:threat_perceptions")

print(output, 
      type = "latex", 
      include.rownames = TRUE)

# clean
rm(list = ls())